1   /*
2    * Copyright (C) 2008 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.collect.testing.testers;
18  
19  import com.google.common.annotations.GwtCompatible;
20  import com.google.common.collect.testing.AbstractCollectionTester;
21  import com.google.common.collect.testing.Helpers;
22  
23  import java.util.Collection;
24  import java.util.List;
25  
26  /**
27   * Base class for list testers.
28   *
29   * @author George van den Driessche
30   */
31  @GwtCompatible
32  public class AbstractListTester<E> extends AbstractCollectionTester<E> {
33    /*
34     * Previously we had a field named list that was initialized to the value of
35     * collection in setUp(), but that caused problems when a tester changed the
36     * value of list or collection but not both.
37     */
38    protected final List<E> getList() {
39      return (List<E>) collection;
40    }
41  
42    /**
43     * {@inheritDoc}
44     * <p>
45     * The {@code AbstractListTester} implementation overrides
46     * {@link AbstractCollectionTester#expectContents(Collection)} to verify that
47     * the order of the elements in the list under test matches what is expected.
48     */
49    @Override protected void expectContents(Collection<E> expectedCollection) {
50      List<E> expectedList = Helpers.copyToList(expectedCollection);
51      // Avoid expectEquals() here to delay reason manufacture until necessary.
52      if (getList().size() != expectedList.size()) {
53        fail("size mismatch: " + reportContext(expectedList));
54      }
55      for (int i = 0; i < expectedList.size(); i++) {
56        E expected = expectedList.get(i);
57        E actual = getList().get(i);
58        if (expected != actual &&
59            (expected == null || !expected.equals(actual))) {
60          fail("mismatch at index " + i + ": " + reportContext(expectedList));
61        }
62      }
63    }
64  
65    /**
66     * Used to delay string formatting until actually required, as it
67     * otherwise shows up in the test execution profile when running an
68     * extremely large numbers of tests.
69     */
70    private String reportContext(List<E> expected) {
71      return Platform.format("expected collection %s; actual collection %s",
72                             expected, this.collection);
73    }
74  }